//
//  nxzServiceConnector.m
//  projectAlcohol
//
//  Created by karan kadakia on 11/14/13.
//  Copyright (c) 2013 home. All rights reserved.
//

#import "nxzServiceConnector.h"

@implementation nxzServiceConnector {
    NSData *receivedData;
}

-(void)getTest {
    
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/project-alcohol/index.php"]];
    
    [request setHTTPMethod:@"GET"];
    //Select what task will the server perform
    [request addValue:@"getValues" forHTTPHeaderField:@"METHOD"];
    //initialize NSURL connection with the request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if (!connection) {
        NSLog(@"Connection Failed");
    }
}

-(void)postTest {
    
    //build up a request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/project-alcohol/index.php"]];
    
    [request setHTTPMethod:@"POST"];
    [request addValue:@"getValues" forHTTPHeaderField:@"METHOD"];
    
    //Create data that will be sent in the post
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:@2 forKey:@"value1"];
    [dictionary setValue:@"this was sent from ios to server" forKey:@"value2"];
    
    //serialize dictionary data as json
    NSData *data = [[dictionary copy] JSONValue];
    
    //set the data as the post body
    [request setHTTPBody:data];
    [request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if (!connection) {
        NSLog(@"Connection Failed");
    }
}

#pragma mark - Data connection delegate -

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //exectuted when the connection recieves data
    
    receivedData = data;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //executed when the connection fails
    
    NSLog(@"Connectio Failed with error %@",error.localizedDescription);
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Request Complete, received %d bytes of data",receivedData.length);
    //send data to the delegate
    [self.delegate requestReturnedData:receivedData];
}
@end
